package tech.yunland.shop.web;


import com.moyuer.bsf.common.Pagination;
import com.moyuer.bsf.domain.model.ConfigItem;
import com.moyuer.bsf.domain.model.Role;
import com.moyuer.bsf.domain.model.User;
import com.moyuer.bsf.domain.model.UserRoles;
import com.moyuer.bsf.domain.service.ConfigItemService;
import com.moyuer.bsf.domain.service.UserService;
import com.moyuer.bsf.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tech.yunland.shop.domain.model.ChargeBill;
import tech.yunland.shop.domain.model.UserPrize;
import tech.yunland.shop.domain.service.JobPrizeService;
import tech.yunland.shop.domain.service.UserPrizeService;

import java.util.*;

/**
 * 员工提成
 *
 * @author 袁首京<yuanshoujing@gmail.com>
 */
@RestController
@RequestMapping("/user/prize")
public class UserPrizeController extends BaseController {

    @Autowired
    private ConfigItemService configItemService;

    @Autowired
    private UserPrizeService userPrizeService;

    @Autowired
    private JobPrizeService jobPrizeService;

    @Autowired
    private UserService userService;
    /**
     * 保存员工提成
     *
     * @param userPrize
     */
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public void save(@RequestBody UserPrize userPrize) {

        if (userPrize.getOrganId() == null) {
            userPrize.setOrganId(primaryOrganId);
        }

        // 判断创建人
        if (userPrize.getCreator() == null) {
            userPrize.setCreator(this.currentUser);
        }



        Set a =new HashSet<>();
        ChargeBill b1 = new ChargeBill();
        a.add(b1);
        ChargeBill b2 = new ChargeBill();
        a.add(b2);


        userPrizeService.save(userPrize);

        // 保存日志
        saveLog("设置员工 [" + userPrize.getOwnerName() + "] 的提成为 [" + userPrize.getPrizeValue() + "]");
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public UserPrize get(@PathVariable String id) {
        return userPrizeService.get(id);
    }

    /**
     * 根据 id 标记删除
     *
     * @param id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void delete(@PathVariable String id) {
        UserPrize userPrize = userPrizeService.get(id);
        String userName = userPrize.getOwnerName();
        userPrizeService.delete(id);
        saveLog("删除员工 [" + userName + "] 的提成设置");
    }

    /**
     * 根据入参查询结果集
     *
     * @param page
     * @param states
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public Pagination<UserPrize> getResultInfo(
            @RequestParam(required = false) String param,
            @RequestParam(required = false) List<Integer> states,
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer rows) {


        if (states == null) {
            states = new ArrayList<>();
            states.add(0);
            states.add(1);
        }

        Pagination<UserPrize> result = new Pagination<UserPrize>(page, rows);
        int startIdx = result.getStartIdx();

        int count = userPrizeService.getResultSize(param, states, organIds);
        List<UserPrize> records = userPrizeService.getResultList(param, states, organIds, startIdx, rows);

        result.setCount(count);
        result.setRecords(records);

        return result;
    }

    /**
     * 获取所有没有设置提成的员工
     */
    @RequestMapping(value = "/userNoPrize",method = RequestMethod.GET)
        public Pagination<User> getUser(
                @RequestParam(required = false) List<String> organIds,
                @RequestParam(required = false) Integer page,
                @RequestParam(required = false) Integer rows
    ) {
            if (organIds == null || organIds.size() <= 0) {
                organIds = this.organIds;
            }
            Pagination<User> result = new Pagination<>(page, rows);
            List<User> records = userPrizeService.getUser(organIds);
            result.setRecords(records);
            return result;
    }


    /**
     * 获取所有设置过提成的职位
     *
     * @param page
     * @param rows
     * @param params
     * @return
     */
    @RequestMapping(value = "/jobs", method = RequestMethod.GET)
    public Pagination<HashMap<String, Object>> getJobInfo(@RequestParam(required = false) String params,
                                                          @RequestParam(required = false) Integer page,
                                                          @RequestParam(required = false) Integer rows) {
        Pagination<HashMap<String, Object>> result = new Pagination<HashMap<String, Object>>(page, rows);
        int startIdx = result.getStartIdx();

        // 获取当前机构的提成类型
        List<ConfigItem> configItems = configItemService.getList("prize_type", primaryOrganId);
        if (configItems == null || configItems.size() != 1) {
            throw new RuntimeException("未正确设置提成类型");
        }

        ConfigItem configItem = configItems.get(0);

        if ("none".equals(configItem.getValue())) {
            throw new RuntimeException("未开启提成设置");
        }

        // 查当前机构状态为生效的记录
        List<Integer> states = new ArrayList<Integer>();
        states.add(1);

        List<String> organIds = new ArrayList<String>();
        organIds.add(primaryOrganId);

        int count = 0;
        List<HashMap<String, Object>> records = new ArrayList<>();

        if ("user".equalsIgnoreCase(configItem.getValue())) {

            count = userPrizeService.getResultSize(params, states, this.organIds);
            List<UserPrize> userPrizes = userPrizeService.getResultList(params, states, this.organIds, startIdx, rows);
            for (UserPrize userPrize : userPrizes) {
                if (userPrize.getOwner().getUserRoles() == null || userPrize.getOwner().getUserRoles().size() == 0) {
                    throw new RuntimeException("未给员工" + userPrize.getOwnerName() + "设置职位");
                }

//                for (UserRoles userRoles : userPrize.getOwner().getUserRoles()) {
//                    HashMap<String, Object> keyValue = new HashMap<>();
//                    keyValue.put("roleId", userRoles.getRole().getId());
//                    keyValue.put("roleName", userRoles.getRole().getName());
//                    keyValue.put("userId", userPrize.getOwnerId());
//                    keyValue.put("userName", userPrize.getOwnerName());
//                    keyValue.put("id", userRoles.getId());
//                    keyValue.put("portraitName", userPrize.getOwner().getPortraitName());
//                    keyValue.put("ujname", userPrize.getOwnerName()+"("+userRoles.getRole().getName()+")");
//                    records.add(keyValue);
//                }
                HashMap<String, Object> keyValue = new HashMap<>();
                User owner = userPrize.getOwner();
//                Set<UserRoles> userRoles = owner.getUserRoles();
                List<UserRoles> userRoles = owner.getUserRoles();
                UserRoles next = userRoles.iterator().next();
                keyValue.put("roleId", next.getRole().getId());
                keyValue.put("roleName", userPrize.getOwner().getUserRoleNames());
                keyValue.put("userId", userPrize.getOwnerId());
                keyValue.put("userName", userPrize.getOwnerName());
//                keyValue.put("id", userRoles.getId());
                keyValue.put("portraitName", userPrize.getOwner().getPortraitName());
                keyValue.put("ujname", userPrize.getOwnerName()+"("+userPrize.getOwner().getUserRoleNames()+")");
                records.add(keyValue);
            }
        }
        else if ("job".equalsIgnoreCase(configItem.getValue())) {
            count = jobPrizeService.getJobSize(organIds, params);
            List<UserRoles> info = jobPrizeService.getJobInfo(this.organIds, params, startIdx, rows);

            for (UserRoles userRoles : info) {
                User user = userRoles.getUser();
                Role role = userRoles.getRole();
                HashMap<String, Object> keyValue = new HashMap<>();
                keyValue.put("roleId", role.getId());
                keyValue.put("roleName", role.getName());
                keyValue.put("userId", user.getId());
                keyValue.put("userName", user.getName());
                keyValue.put("id", userRoles.getId());
                keyValue.put("portraitName", user.getPortraitName());
                keyValue.put("ujname", user.getName()+"("+role.getName()+")");
                records.add(keyValue);
            }
        }
        else {
            throw new RuntimeException("未正确设置提成类型");
        }

        result.setCount(count);
        result.setRecords(records);

        return result;
    }
}
